package com.example.demo.config.datasource;

import com.alibaba.druid.pool.DruidDataSource;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * 数据源配置
 *
 * @author wuhong-016
 * @version v1.0.0
 * @time: 2021/10/16 17:19
 */
@Slf4j
@Configuration
public class DataSourceConfig {

    private static Logger logger = LoggerFactory.getLogger(DataSourceConfig.class);

    public static final String PRIMARY_DATA_SOURCE = "primaryDataSource";
    public static final String SECOND_DATA_SOURCE = "secondDataSource";

    @Bean
    public DataSource dataSource() throws Exception {
        DynamicDataSource DynamicDataSource = new DynamicDataSource();

        Map<Object, Object> dataSourceMap = new HashMap<>();
        dataSourceMap.put(PRIMARY_DATA_SOURCE, getPrimaryDataSource());
        dataSourceMap.put(SECOND_DATA_SOURCE, getSecondDataSource());

        // 默认为monitor的数据源
        DynamicDataSource.setDefaultTargetDataSource(getPrimaryDataSource());
        DynamicDataSource.setTargetDataSources(dataSourceMap);

        return DynamicDataSource;
    }


    @Value("${spring.datasource.primaryDataSource.driverClassName}")
    private String primaryDriverClassName;
    @Value("${spring.datasource.primaryDataSource.url}")
    private String primaryUrl;
    @Value("${spring.datasource.primaryDataSource.username}")
    private String primaryUsername;
    @Value("${spring.datasource.primaryDataSource.password}")
    private String primaryPassword;

    public DataSource getPrimaryDataSource() throws Exception {
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName(primaryDriverClassName);
        druidDataSource.setUrl(primaryUrl);
        druidDataSource.setUsername(primaryUsername);
        druidDataSource.setPassword(primaryPassword);
        return druidDataSource;
    }

    @Value("${spring.datasource.secondDataSource.driverClassName}")
    private String secondDriverClassName;
    @Value("${spring.datasource.secondDataSource.url}")
    private String secondUrl;
    @Value("${spring.datasource.secondDataSource.username}")
    private String secondUsername;
    @Value("${spring.datasource.secondDataSource.password}")
    private String secondPassword;

    public DataSource getSecondDataSource() throws Exception {
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName(secondDriverClassName);
        druidDataSource.setUrl(secondUrl);
        druidDataSource.setUsername(secondUsername);
        druidDataSource.setPassword(secondPassword);
        return druidDataSource;
    }

}